<template>
  <!-- 商品添加修改页面 -->
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? '新增商品' : '编辑商品'"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px">
      <el-form-item prop="groupName" label="分类名称">
        <ComSelectPage ref="newPageSelect" @selectPageChange="e=>dataForm.groupName=e"
        :getUrl="{
        url:'/api/productGroup/page',
        method:'get',
        params:{page: 1,limit: 10,total: 0},
      }" clearable :defaultValue="dataForm.groupName" selectLabel="groupName" selectValue="groupName"></ComSelectPage>
      </el-form-item>
      <el-form-item prop="showState" label="上架状态">
        <ren-radio-group v-model="dataForm.showState" dict-type="show_state"></ren-radio-group>
      </el-form-item>
      <el-form-item prop="productType" label="商品类型">
        <ren-select v-model="dataForm.productType" dict-type="product_type" placeholder="请选择类型（选填）"></ren-select>
      </el-form-item>
<!--      <el-form-item prop="single" label="是否加入购物车">-->
<!--        <ren-radio-group v-model="dataForm.single" dict-type="single"></ren-radio-group>-->
<!--      </el-form-item>-->
      <el-form-item prop="productName" label="商品名称">
        <el-input v-model="dataForm.productName" placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item prop="productDesc" label="商品介绍">
        <el-input v-model="dataForm.productDesc" placeholder="请输入商品介绍"></el-input>
      </el-form-item>
<!--      <el-form-item prop="serviceList" label="服务内容">-->
<!--        <el-input v-model="dataForm.serviceList" placeholder="请输入服务内容"></el-input>-->
<!--      </el-form-item>-->
      <el-form-item prop="price" label="起购价">
        <el-input-number v-model="dataForm.price" :precision="2" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="marketPrice" label="划线价">
        <el-input-number v-model="dataForm.marketPrice" :precision="2" :min="0"></el-input-number>
      </el-form-item>
<!--      <el-form-item prop="stock" label="库存数量">-->
<!--        <el-input-number v-model="dataForm.stock" :precision="0" :min="0"></el-input-number>-->
<!--      </el-form-item>-->
      <el-form-item prop="sold" label="已售数量">
        <el-input-number v-model="dataForm.sold" :precision="0" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="sort" label="排序">
        <el-input-number v-model="dataForm.sort" :precision="0" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="imgUrl" label="图片">
        <div class="flex_center flex_wrap">
          <div class="img_con" v-if="dataForm.imgUrl">
            <el-image class="deduct_img" :src="dataForm.imgUrl" :preview-src-list="[dataForm.imgUrl]"/>
            <i class="el-icon-error remove_img" @click="cancelImg(dataForm.imgUrl)"/>
          </div>
          <com-upload v-show="!dataForm.imgUrl" @get-url="getUrlOne"></com-upload>
        </div>
        <div style="color:#909399;"><el-icon class="el-icon-info"></el-icon>建议上传2:1的图片</div>
      </el-form-item>
      <el-form-item prop="details" label="商品详情" v-loading="loading" v-if="visible">
        <div style="border: 1px solid #ccc;">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
          />
          <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="dataForm.details"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import Cookies from "js-cookie";
import axios from "axios";
import { Base64 } from 'js-base64';
import * as imageConversion from "image-conversion";
import {Message, Notification} from "element-ui";

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      visible: false,
      loading: false,
      url: '',
      dataForm: {
        id: '',
        imgUrl: '',             //商品的图片路径或链接
        groupName: '',          //商品所属的分类或类别
        showState: '',          //上架状态，0不展示，1展示
        productType: '',        //商品类型
        productName: '',        //商品的名称
        productDesc: '',        //商品的描述或介绍
        price: '',              //商品的价格
        marketPrice: '',        //商品的划线价格
        stock: '',              //商品的库存数量
        sold: '',               //商品的已售数量
        sort: '',               //用来显示商品在列表中的顺序
        details:'',             //商品的详细介绍
        // serviceList:'',         //服务内容
        single:''               //是否允许单买
      },
      //传给子组件的参数
      // getUrl:{
      //   url:'/api/productGroup/page',
      //   method:'get',
      //   //分页所需参数
      //   params:{
      //     page: 1,                    // 当前页码
      //     limit: 10,                  // 每页数
      //     total: 0,                   // 总条数
      //   },
      // },
      editor: null,
      toolbarConfig: {
        excludeKeys: [],//屏蔽图片链接上传，视频上传
      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 上传图片配置
          uploadImage: {
            customUpload: this.uploadImage // 自定义上传方法
          },
          // 上传视频配置
          uploadVideo: {
            customUpload: this.uploadVideo // 自定义上传方法
          }
        }
      },
      mode: 'default', // or 'simple'
    }
  },
  computed: {
    dataRule() {
      return {
        groupName: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        showState: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        productName: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        // productDesc: [
        //   {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        // ],
        price: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        // stock: [
        //   {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        // ],
        imgUrl: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
      }
    },
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo() {
      this.$http.get(`/api/product/${this.dataForm.id}`).then(({data: res}) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {
      })
    },
    //上传图片
    async uploadImage (file, insertFn) {
      const form = new FormData()
      this.loading = true
      const blobFile = await imageConversion.compressAccurately(file, {size:`${window.SITE_CONFIG['imageConversionQuality']}`,type:'image/png'})// 设置压缩大小默认700k
      const resFile = new File([blobFile], file.name, {type: blobFile.type})// blob转file对象
      form.append('file', resFile)
      // 发送post请求
      const instance = axios.create({
        baseURL: `${window.SITE_CONFIG['apiURL']}`,
        timeout: `${window.SITE_CONFIG['uploadTimeout']}`,
        headers: {
          'token': Cookies.get('token'),//接口需要的token
          'Content-Type': 'application/json'
        }
      })
      instance.post(`/sys/oss/upload?token=${Cookies.get('token')}`, form
      ).then(res => {
        Notification.success({
          title: '成功',
          message: res.data.msg||'上传成功！',
          type: 'success'
        })
        this.loading = false
        let {data} = res.data
        insertFn(data.src)
      }).catch(err => {
        this.loading = false
        console.log(err)
        Message.error(err.data.msg||'上传失败')
      })
    },
    //上传视频
    async uploadVideo(file, insertFn) {
      const { type } = file
      if(type.indexOf("video") < 0) {
        Message.warning("请选择上传视频!")
        return false
      }
      if(file.size > `${window.SITE_CONFIG['uploadVideoMaxSize']}`* 1024 * 1024) {
        Message.warning(`视频大小不能超过${window.SITE_CONFIG['uploadVideoMaxSize']}M!`)
        return false
      }
      const form = new FormData()
      form.append("file", file)
      // 发送post请求
      this.loading = true
      const instance = axios.create({
        baseURL: `${window.SITE_CONFIG['apiURL']}`,
        timeout: `${window.SITE_CONFIG['uploadTimeout']}`,
        headers: {
          'token': Cookies.get('token'),//接口需要的token
          'Content-Type': 'application/json'
        }
      })
      instance.post(`/sys/oss/upload?token=${Cookies.get('token')}`, form
      ).then(res => {
        Notification.success({
          title: '成功',
          message: res.data.msg||'上传成功！',
          type: 'success'
        })
        this.loading = false
        let {data} = res.data
        insertFn(data.src)
      }).catch(err => {
        this.loading = false
        console.log(err)
        Message.error(err.data.msg)
      })
    },
    // 添加图片
    // 添加单图添加
    getUrlOne(getUrl){
      this.dataForm.imgUrl = getUrl
    },
    // 删除服务器图片
    cancelImg(url) {
      this.$http({
        url: `/sys/oss/deleteByUrl`,
        method: 'delete',
        data: {url: url},
      }).then(({data: res}) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm.imgUrl = ''
        if (this.dataForm.id){
          this.$http['put']('/api/product', this.dataForm).then(({data: res}) => {
          }).catch((err) => {
            this.$message.error(err.msg)
          })
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        const item = {...this.dataForm}
        item.details = Base64.encode(item.details)
        this.$http[!this.dataForm.id ? 'post' : 'put']('/api/product', item).then(({data: res}) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {
        })
      })
    }, 1000, {'leading': true, 'trailing': false}),
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      !this.dataForm.id? this.editor.clear():''
    },
  }
}
</script>
<style>
.el-upload el-upload-picture-card {
  display: none;
}

.img_con {
  position: relative;
  display: flex;
}

.deduct_img {
  width: 140px;
  height: 140px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.remove_img {
  position: absolute;
  right: 5px;
  top: -5px;
  color: red;
  cursor: pointer;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css">
</style>
